<?php

namespace App\Service;

use App\Amqp\Producer\MailProducer;
use App\Components\Mail;
use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use Hyperf\Amqp\Producer;
use Hyperf\Context\ApplicationContext;
use Hyperf\Contract\TranslatorInterface;
use Hyperf\Logger\LoggerFactory;

class IndexService
{
    public function inf(int $id) {
        if ($id <= 0) {
            //throw new BusinessException("id无效");
            //throw new BusinessException(\Hyperf\Translation\trans('params.id_invalid'));
//            $translator = ApplicationContext::getContainer()->get(TranslatorInterface::class);
//            $translator->setLocale('ja');
            //throw new BusinessException(\Hyperf\Translation\trans('params.id_invalid'));
            //throw new BusinessException(ErrorCode::getMessage(ErrorCode::PARAMS_ID_INVALID));
            throw new BusinessException(ErrorCode::PARAMS_ID_INVALID);
        }
        return ['info' => 'data info'];
    }

    public function sendMail() {
        $startTime = microtime(true);
        \Hyperf\Coroutine\co(function () {
            $mail = ApplicationContext::getContainer()->get(Mail::class);
            $mail->to('liuhaitao@whty.com.cn')->send('测试标题', '<b style="color: #676060;">邮件测试内容</b>');
            $log = ApplicationContext::getContainer()->get(LoggerFactory::class)->get('co');
            $log->info("邮件已发送");
        });
        $runTime = microtime(true) - $startTime;
        return ['time' => date('Y-m-d H:i:s'), 'runtime' => '耗时: '.$runTime.'s'];
    }

    public function sendMailMq()
    {
        $startTime = microtime(true);
        $mailInfo = [
            'to' => 'liuhaitao@whty.com.cn',
            'subject' => '邮件测试标题111',
            'body' => '<b style="color: #f00;">邮件测试内容222</b>',
        ];
        $message = new MailProducer($mailInfo);
        $producer = ApplicationContext::getContainer()->get(Producer::class);
        $producer->produce($message);
        $runTime = microtime(true) - $startTime;
        return ['time' => date('Y-m-d H:i:s'), 'runtime' => '耗时: '.$runTime.'s'];
    }

}